package com.it.share;

import org.apache.ibatis.builder.StaticSqlSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.h2.jdbcx.JdbcConnectionPool;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.ArrayList;

@ComponentScan(basePackages = "com.it.share")
@Configuration
public class AppConfig {

    @Bean
    public DataSource b2() {
        DataSource dataSource = JdbcConnectionPool.create(
                "jdbc:h2:mem:test1",
                "root",
                "root"
        );
        return dataSource;
    }

    @Bean
    public org.apache.ibatis.session.Configuration b1(DataSource dataSource) {
        JdbcTransactionFactory factory = new JdbcTransactionFactory();
        Environment environment = new Environment("1", factory, dataSource);

        org.apache.ibatis.session.Configuration m = new org.apache.ibatis.session.Configuration(environment);

        MappedStatement.Builder b = new MappedStatement.Builder(m,
                "sss", new StaticSqlSource(m, "select 1"), SqlCommandType.SELECT);
        b.resultMaps(new ArrayList<ResultMap>() {{
            add(new ResultMap.Builder(m, "1", Integer.class, new ArrayList<>(0)).build());
        }});

        m.addMappedStatement(b.build());
        return m;
    }

    @Bean
    public SqlSessionFactory b0(org.apache.ibatis.session.Configuration mConfig) {
        DefaultSqlSessionFactory sqlSessionFactory = new DefaultSqlSessionFactory(mConfig);
        return sqlSessionFactory;
    }
}
